package view.admin;

import controller.UserController;
import dao.CreditDAO;
import model.User;
import model.CreditLog;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 信誉分管理面板
 */
public class CreditManagementPanel extends JPanel {
    private UserController userController;
    private CreditDAO creditDAO;

    // 表格组件
    private JTable userTable;
    private DefaultTableModel userTableModel;
    private TableRowSorter<DefaultTableModel> userTableSorter;

    private JTable logTable;
    private DefaultTableModel logTableModel;
    private TableRowSorter<DefaultTableModel> logTableSorter;

    // 控制组件
    private JTextField searchField;
    private JButton searchButton;
    private JButton adjustCreditButton;
    private JButton refreshButton;

    // 信誉分调整对话框组件
    private JDialog adjustDialog;
    private JTextField adjustAmountField;
    private JTextArea reasonArea;

    public CreditManagementPanel() {
        this.userController = new UserController();
        this.creditDAO = new CreditDAO();

        initComponents();
        setupLayout();
        setupEventListeners();
        refreshData();
    }

    private void initComponents() {
        setLayout(new BorderLayout());
        setBackground(new Color(248, 250, 252));

        // 用户表格
        String[] userColumns = { "用户ID", "学号", "姓名", "信誉分", "等级", "注册时间" };
        userTableModel = new DefaultTableModel(userColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        userTable = new JTable(userTableModel);
        userTableSorter = new TableRowSorter<>(userTableModel);
        userTable.setRowSorter(userTableSorter);

        // 日志表格
        String[] logColumns = { "时间", "用户", "学号", "变化", "变化后", "原因", "类型" };
        logTableModel = new DefaultTableModel(logColumns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        logTable = new JTable(logTableModel);
        logTableSorter = new TableRowSorter<>(logTableModel);
        logTable.setRowSorter(logTableSorter);

        // 控制组件
        searchField = new JTextField();
        searchButton = new JButton("搜索");
        adjustCreditButton = new JButton("手动调整");
        refreshButton = new JButton("刷新数据");

        // 美化组件
        styleComponents();
    }

    private void setupLayout() {
        // 顶部控制面板
        JPanel controlPanel = createControlPanel();
        add(controlPanel, BorderLayout.NORTH);

        // 主要内容 - 使用上下分割的布局
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.setResizeWeight(0.6); // 用户表格占60%，日志表格占40%

        // 用户表格面板
        JPanel userPanel = createUserTablePanel();
        splitPane.setTopComponent(userPanel);

        // 日志表格面板
        JPanel logPanel = createLogTablePanel();
        splitPane.setBottomComponent(logPanel);

        add(splitPane, BorderLayout.CENTER);
    }

    private JPanel createControlPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 渐变背景
                GradientPaint gradient = new GradientPaint(0, 0, Color.WHITE, 0, getHeight(), new Color(248, 252, 255));
                g2d.setPaint(gradient);
                g2d.fillRect(0, 0, getWidth(), getHeight());

                // 底部分割线
                g2d.setColor(new Color(226, 232, 240));
                g2d.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1);
            }
        };

        panel.setLayout(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(20, 30, 20, 30));

        // 左侧：标题
        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setOpaque(false);

        JLabel titleLabel = new JLabel("⭐ 信誉分管理");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 24));
        titleLabel.setForeground(new Color(30, 41, 59));

        JLabel subLabel = new JLabel("管理用户信誉分和查看变更记录");
        subLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        subLabel.setForeground(new Color(100, 116, 139));

        leftPanel.add(titleLabel, BorderLayout.NORTH);
        leftPanel.add(subLabel, BorderLayout.CENTER);

        // 右侧：控制组件
        JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 15, 0));
        rightPanel.setOpaque(false);

        JLabel searchLabel = new JLabel("搜索用户");
        searchLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        searchLabel.setForeground(new Color(71, 85, 105));

        searchField.setPreferredSize(new Dimension(200, 38));

        rightPanel.add(searchLabel);
        rightPanel.add(searchField);
        rightPanel.add(searchButton);
        rightPanel.add(adjustCreditButton);
        rightPanel.add(refreshButton);

        panel.add(leftPanel, BorderLayout.WEST);
        panel.add(rightPanel, BorderLayout.EAST);

        return panel;
    }

    private JPanel createUserTablePanel() {
        JPanel panel = new JPanel(new BorderLayout(0, 15));
        panel.setOpaque(false);
        panel.setBorder(BorderFactory.createEmptyBorder(20, 30, 10, 30));

        JLabel titleLabel = new JLabel("用户信誉分状态");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        titleLabel.setForeground(new Color(30, 41, 59));

        JScrollPane scrollPane = new JScrollPane(userTable);
        scrollPane.setBorder(BorderFactory.createLineBorder(new Color(229, 231, 235), 1));

        panel.add(titleLabel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createLogTablePanel() {
        JPanel panel = new JPanel(new BorderLayout(0, 15));
        panel.setOpaque(false);
        panel.setBorder(BorderFactory.createEmptyBorder(10, 30, 20, 30));

        JLabel titleLabel = new JLabel("信誉分变更记录");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        titleLabel.setForeground(new Color(30, 41, 59));

        JScrollPane scrollPane = new JScrollPane(logTable);
        scrollPane.setBorder(BorderFactory.createLineBorder(new Color(229, 231, 235), 1));

        panel.add(titleLabel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private void styleComponents() {
        // 美化搜索框
        searchField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        searchField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(203, 213, 225), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12)));

        // 美化按钮
        styleButton(searchButton, new Color(59, 130, 246));
        styleButton(adjustCreditButton, new Color(239, 68, 68));
        styleButton(refreshButton, new Color(34, 197, 94));

        // 美化表格
        styleTable(userTable);
        styleTable(logTable);
    }

    private void styleButton(JButton button, Color backgroundColor) {
        button.setPreferredSize(new Dimension(100, 38));
        button.setBackground(backgroundColor);
        button.setForeground(Color.WHITE);
        button.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        button.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor.darker());
                }
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor);
                }
            }
        });
    }

    private void styleTable(JTable table) {
        table.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        table.setRowHeight(35);
        table.setSelectionBackground(new Color(219, 234, 254));
        table.setSelectionForeground(new Color(30, 58, 138));
        table.setGridColor(new Color(243, 244, 246));
        table.setShowGrid(true);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // 表头样式
        table.getTableHeader().setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        table.getTableHeader().setBackground(new Color(249, 250, 251));
        table.getTableHeader().setForeground(new Color(75, 85, 99));
        table.getTableHeader().setBorder(BorderFactory.createLineBorder(new Color(229, 231, 235), 1));
    }

    private void setupEventListeners() {
        // 搜索按钮
        searchButton.addActionListener(_ -> performSearch());

        // 搜索框回车
        searchField.addActionListener(_ -> performSearch());

        // 调整信誉分按钮
        adjustCreditButton.addActionListener(_ -> showAdjustCreditDialog());

        // 刷新按钮
        refreshButton.addActionListener(_ -> refreshData());

        // 用户表格选择事件
        userTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = userTable.getSelectedRow();
                adjustCreditButton.setEnabled(selectedRow >= 0);

                if (selectedRow >= 0) {
                    int userIdColumn = 0;
                    int userId = (Integer) userTable.getValueAt(selectedRow, userIdColumn);
                    loadUserCreditLogs(userId);
                }
            }
        });
    }

    private void performSearch() {
        String searchText = searchField.getText().trim();
        if (searchText.isEmpty()) {
            userTableSorter.setRowFilter(null);
        } else {
            userTableSorter.setRowFilter(RowFilter.regexFilter("(?i)" + searchText));
        }
    }

    private void showAdjustCreditDialog() {
        int selectedRow = userTable.getSelectedRow();
        if (selectedRow < 0) {
            JOptionPane.showMessageDialog(this, "请先选择一个用户", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 获取选中的用户信息
        int userId = (Integer) userTable.getValueAt(selectedRow, 0);
        String studentId = (String) userTable.getValueAt(selectedRow, 1);
        String name = (String) userTable.getValueAt(selectedRow, 2);
        int currentScore = (Integer) userTable.getValueAt(selectedRow, 3);

        // 创建调整对话框
        createAdjustCreditDialog(userId, studentId, name, currentScore);
    }

    private void createAdjustCreditDialog(int userId, String studentId, String name, int currentScore) {
        adjustDialog = new JDialog((Frame) SwingUtilities.getWindowAncestor(this), "调整信誉分", true);
        adjustDialog.setSize(400, 400);
        adjustDialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new BorderLayout(0, 20));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 用户信息
        JPanel userInfoPanel = new JPanel(new GridLayout(3, 2, 10, 10));
        userInfoPanel.add(new JLabel("学号："));
        userInfoPanel.add(new JLabel(studentId));
        userInfoPanel.add(new JLabel("姓名："));
        userInfoPanel.add(new JLabel(name));
        userInfoPanel.add(new JLabel("当前信誉分："));
        userInfoPanel.add(new JLabel(String.valueOf(currentScore)));

        // 调整信息
        JPanel adjustPanel = new JPanel(new BorderLayout(0, 10));

        JPanel amountPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        amountPanel.add(new JLabel("调整分数："));
        adjustAmountField = new JTextField(10);
        amountPanel.add(adjustAmountField);
        amountPanel.add(new JLabel("(正数为增加，负数为扣减)"));

        JPanel reasonPanel = new JPanel(new BorderLayout(0, 5));
        reasonPanel.add(new JLabel("调整原因："), BorderLayout.NORTH);
        reasonArea = new JTextArea(4, 20);
        reasonArea.setBorder(BorderFactory.createLineBorder(Color.GRAY));
        reasonPanel.add(new JScrollPane(reasonArea), BorderLayout.CENTER);

        adjustPanel.add(amountPanel, BorderLayout.NORTH);
        adjustPanel.add(reasonPanel, BorderLayout.CENTER);

        // 按钮
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton confirmButton = new JButton("确认调整");
        JButton cancelButton = new JButton("取消");

        styleButton(confirmButton, new Color(34, 197, 94));
        styleButton(cancelButton, new Color(156, 163, 175));

        confirmButton.addActionListener(_ -> performCreditAdjustment(userId, currentScore));
        cancelButton.addActionListener(_ -> adjustDialog.dispose());

        buttonPanel.add(confirmButton);
        buttonPanel.add(cancelButton);

        panel.add(userInfoPanel, BorderLayout.NORTH);
        panel.add(adjustPanel, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        adjustDialog.add(panel);
        adjustDialog.setVisible(true);
    }

    private void performCreditAdjustment(int userId, int currentScore) {
        try {
            String amountText = adjustAmountField.getText().trim();
            String reason = reasonArea.getText().trim();

            if (amountText.isEmpty()) {
                JOptionPane.showMessageDialog(adjustDialog, "请输入调整分数", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (reason.isEmpty()) {
                JOptionPane.showMessageDialog(adjustDialog, "请输入调整原因", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            int adjustAmount = Integer.parseInt(amountText);
            int newScore = currentScore + adjustAmount;

            if (newScore < 0) {
                JOptionPane.showMessageDialog(adjustDialog, "调整后信誉分不能小于0", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (newScore > 150) {
                JOptionPane.showMessageDialog(adjustDialog, "调整后信誉分不能超过150", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 执行调整
            boolean success = creditDAO.adjustUserCreditScore(userId, adjustAmount, reason);

            if (success) {
                JOptionPane.showMessageDialog(adjustDialog, "信誉分调整成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                adjustDialog.dispose();
                refreshData();
            } else {
                JOptionPane.showMessageDialog(adjustDialog, "调整失败，请重试", "错误", JOptionPane.ERROR_MESSAGE);
            }

        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(adjustDialog, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(adjustDialog, "调整失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void loadUserCreditLogs(int userId) {
        SwingUtilities.invokeLater(() -> {
            try {
                logTableModel.setRowCount(0);

                LocalDate startDate = LocalDate.now().minusMonths(3);
                LocalDate endDate = LocalDate.now();
                List<CreditLog> logs = creditDAO.getUserCreditLogs(userId, startDate, endDate);

                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd HH:mm");

                for (CreditLog log : logs) {
                    Object[] row = {
                            log.getCreateTime().format(formatter),
                            log.getUser() != null ? log.getUser().getName() : "未知",
                            log.getUser() != null ? log.getUser().getStudentId() : "未知",
                            log.getScoreChangeText(),
                            log.getScoreAfter(),
                            log.getReason(),
                            log.getLogTypeText()
                    };
                    logTableModel.addRow(row);
                }
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "加载信誉分记录失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
    }

    public void refreshData() {
        SwingUtilities.invokeLater(() -> {
            try {
                // 刷新用户表格
                userTableModel.setRowCount(0);
                List<User> users = userController.getAllUsers();

                for (User user : users) {
                    if (user.getUserType() == 0) { // 只显示学生用户
                        Object[] row = {
                                user.getUserId(),
                                user.getStudentId(),
                                user.getName(),
                                user.getCreditScore(),
                                user.getCreditScoreLevel(),
                                user.getCreateTime() != null
                                        ? user.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                                        : "未知"
                        };
                        userTableModel.addRow(row);
                    }
                }

                // 清空日志表格
                logTableModel.setRowCount(0);

                // 禁用调整按钮
                adjustCreditButton.setEnabled(false);

            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "刷新数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
    }
}
